//
//  MyCollectViewController.m
//  SuperRadio
//
//  Created by GYRu on 14-12-30.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "MyCollectViewController.h"
#import "DataBaseHandler.h"
#import "MainPlayerViewController.h"
#import "AlbumDatailsOfList.h"
#import "AlbumDetailsCell.h"
#import "NetHandler.h"
#import "UIColor+AddColor.h"


#import "MainPlayerViewController.h"

#import "AudioPlayer.h"
#import "AudioButton.h"

@interface MyCollectViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *collectTableView;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSMutableArray *collectArr;

@property (nonatomic, assign) NSInteger cellTag;

@property (nonatomic, retain)AudioButton *audioBtn;

@property(nonatomic, retain) MainPlayerViewController *mainPlayVC;

@property (nonatomic, retain)AlbumDetailsCell *cell;
@property (nonatomic, retain)UIImageView *imageBack;
@end

@implementation MyCollectViewController

- (void)viewWillAppear:(BOOL)animated
{
    // 在页面出现的时候查询数据库
    DataBaseHandler *handler = [DataBaseHandler shareInstance];
    [handler openDB];
    self.collectArr = [NSMutableArray array];
    self.arr = [NSMutableArray  arrayWithArray:[handler selectAll]];
    // 判断数组内容
    if (self.arr.count == 0) {
        // 当数组内容为空的时候 在页面上覆盖一张图片
        self.imageBack = [[UIImageView alloc] initWithFrame:self.view.bounds];
        [self.imageBack setImage:[UIImage imageNamed:@"back2.jpg"]];
        self.imageBack.alpha = 0.8;
        [self.view addSubview:_imageBack];
        [_imageBack release];
        self.collectTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }else{
        // 不为空 隐藏图片
        self.imageBack.hidden = YES;
    }
    // 调用数据解析
    [self getInfor];

}

#pragma mark 相关专辑的数据解析
- (void)getInfor
{
    for (AlbumDatailsOfList *list in self.arr) {
        
//        NSLog(@"%@",[list.trackId stringValue]);
        
        NSString *path = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", [list.trackId stringValue]];
        
        [NetHandler getDataWithURL:path completion:^(NSData *data) {
            
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            AlbumDatailsOfList *detail = [[AlbumDatailsOfList alloc] initWithDictionary:result];
            detail.nickname = [[result objectForKey:@"userInfo"] objectForKey:@"nickname"];
            [self.collectArr addObject:detail];
            
            
            if (self.collectArr.count == self.arr.count) {
                [_collectTableView reloadData];
                
            }
            
        }];

        
    }
    
}

#pragma mark 点击播放的按钮

- (void)playLikeAudio:(AudioButton *)button
{
    
    self.audioBtn = button;
    self.cellTag = button.tag;
    _audioPlayer =  [AudioPlayer shareInstance];
    _audioPlayer.imagePath = [[self.collectArr objectAtIndex:button.tag - 10000] coverLarge];
    if ([_audioPlayer.button isEqual: button]) {
        // 如果播放的按钮等于现在按钮 播放
        [_audioPlayer play];
        
    } else {
        // 如果不等于
        _mainPlayVC = [MainPlayerViewController defaultPlayer];
        // 将列表数组中数据全部移除
        [_mainPlayVC.listArr removeAllObjects];
        // 将收藏数组中的内容添加到列表数组
        [_mainPlayVC.listArr addObjectsFromArray:self.collectArr];
        
        _mainPlayVC.trackId = [[self.collectArr objectAtIndex:button.tag - 10000] trackId];
        _mainPlayVC.index = button.tag - 10000;
        [_mainPlayVC showDetailInformation];
        // 播放停止
        [_audioPlayer stop];
        
        _audioPlayer.button = button;
        
        
        _audioPlayer.url = [NSURL URLWithString:[[self.collectArr objectAtIndex:button.tag - 10000] playUrl64]];
        
        [_audioPlayer play];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的收藏";
    
    
    // Do any additional setup after loading the view.
    
    
    self.collectTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    
    self.collectTableView.delegate = self;
    self.collectTableView.dataSource = self;
    
    [self.view addSubview:self.collectTableView];
    [_collectTableView release];
    
    // 让tableView可以编辑
    [self.collectTableView endEditing:YES];
    
    // 注册cell
    [self.collectTableView registerClass:[AlbumDetailsCell class] forCellReuseIdentifier:@"collect"];
    
    
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [backImage setImage:[UIImage imageNamed:@"back1.png"]];
    backImage.alpha = 0.5;
    self.collectTableView.backgroundView = backImage;
    [backImage release];
    
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 100;
   
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.collectArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *str = @"datails";
    
    AlbumDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell == nil || self.cellTag != 10000 + indexPath.row) {
        
        cell = [[[AlbumDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
        [cell.audioButton addTarget:self action:@selector(playLikeAudio:) forControlEvents:UIControlEventTouchUpInside];
    }
    cell.audioButton.tag = indexPath.row + 10000;
    
    if (self.cellTag == 10000 + indexPath.row) {
        [cell.audioButton removeFromSuperview];
        [cell.contentView addSubview:self.audioBtn];
    }
    AlbumDatailsOfList *datailList = [self.collectArr objectAtIndex:indexPath.row];
    
   // NSLog(@"%ld",cell.audioButton.tag);
    
    
    cell.albumDatailsOfList = datailList;
    
    return cell;
    

    
}


#pragma mark 点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UINavigationController *navi = [self.tabBarController.viewControllers objectAtIndex:0];
    
    
    
    self.cell = (AlbumDetailsCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    AlbumDatailsOfList *dataList = [self.collectArr objectAtIndex:indexPath.row];
    
    _mainPlayVC = [MainPlayerViewController defaultPlayer];
    
    
    _mainPlayVC.albumDatail = dataList;
    _mainPlayVC.trackId = dataList.trackId;
    [_mainPlayVC.listArr removeAllObjects];
    [_mainPlayVC.listArr addObjectsFromArray:self.collectArr];
    _mainPlayVC.index = indexPath.row;
    _mainPlayVC.navi = self.navigationController;
    _audioPlayer = [AudioPlayer shareInstance];
    
    // 如果播放的按钮和cell的不相等
    if (![_audioPlayer.button isEqual:_cell.audioButton]) {
        // 音频停止
        [_audioPlayer stop];
        // 让自己的按钮等于cell的
        self.audioBtn = _cell.audioButton;
        
        _audioPlayer.button = _cell.audioButton;
        self.cellTag = _cell.audioButton.tag;
        // 将音频的url赋值
        _audioPlayer.url = [NSURL URLWithString:dataList.playUrl64];
        // 播放音频
        [_audioPlayer play];
        
    }
    
    [_mainPlayVC showDetailInformation];
    
    
    if (navi.topViewController != _mainPlayVC) {

        CATransition *transition = [CATransition animation];
        transition.duration = 0.5f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type = @"push";
        transition.subtype = kCATransitionFromTop;
        transition.delegate = self;
        [navi.view.layer addAnimation:transition forKey:nil];
        
       [navi pushViewController:_mainPlayVC animated:YES];
  
    }
    
    self.tabBarController.selectedIndex = 0;

}



//某一行是否可以编辑
- (BOOL)tableview:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 某一行可以移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


//当点击删除按钮的时候, 会调用这个协议方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    DataBaseHandler *dataHandler = [DataBaseHandler shareInstance];
    // 删除数据
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        
        AlbumDatailsOfList *list = [self.collectArr objectAtIndex:indexPath.row];
        [dataHandler deleteCollectWithTrackId:[list.trackId stringValue]];
        
        
        
        [self.arr removeObjectAtIndex:indexPath.row];
        [self.collectArr removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        
        [tableView reloadData];
        
    }else {
        //        DataBaseHandler *dataHandler = [DataBaseHandler shareInstance];
        //        [dataHandler deleteAllNews];
        //        [self.arr removeAllObjects];
        //        [self.tableView reloadData];
    }
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
